import 'dart:io';

import 'package:args/command_runner.dart';
import 'package:frotools/src/scripts/appledoc_script.dart';

const argCompany = 'cmpy';
const argCompanyID = 'id';
const argCompanyURL = 'url';
const argTarget = 'target';
const argOutput = 'out';
const argProjectName = 'pro';

class DocsCommand extends Command {
  @override
  String get description => '代码生成文档'
      '\n\n代码地址: https://gitee.com/samcoding/appledoc';

  @override
  String get name => 'docs';

  DocsCommand() {
    argParser.addOption(
      argProjectName,
      abbr: 'p',
      help: '项目名',
    );

    argParser.addOption(
      argOutput,
      abbr: 'o',
      help: '输出路径',
      defaultsTo: '${Directory.current.path}/docs',
    );

    argParser.addOption(
      argCompany,
      abbr: 'c',
      help: '公司名',
      defaultsTo: 'segi',
    );

    argParser.addOption(
      argCompanyID,
      abbr: 'd',
      help: '公司ID',
      defaultsTo: 'com.segi.uhome',
    );

    argParser.addOption(
      argCompanyURL,
      abbr: 'u',
      help: '公司官网',
      defaultsTo: 'www.uhomecp.com',
    );

    argParser.addOption(
      argTarget,
      abbr: 't',
      help: '编译平台',
      allowed: ['iphoneos', 'macosx'],
      defaultsTo: 'iphoneos',
    );
  }

  @override
  Future run() async {
    var script = AppledocScript();
    // 检测环境
    if (!(await script.env()) || !(await script.env_docsetutil())) {
      print('环境变量缺失！\n'
          'see: https://gitee.com/samcoding/appledoc');
      return Future.value();
    }

    // 当参数为空时，输出 help
    if (argResults.arguments.isEmpty) {
      printUsage();
      return;
    }

    // 项目文件名
    if (!argResults.wasParsed(argProjectName)) {
      print('${argParser.options[argProjectName].help} 不能为空。');
      return;
    }
    var pro = argResults[argProjectName];

    // 公司名
    var compy = getArgValue(argCompany);
    // 公司ID
    var id = getArgValue(argCompanyID);
    // 公司官网
    var url = getArgValue(argCompanyURL);
    //  编译平台
    var target = getArgValue(argTarget);
    // 输出文件路径
    var out = getArgValue(argOutput);

    // 获取需要生成代码的路径
    var input = Directory.current.path;
    if (argResults.rest.isNotEmpty) input = argResults.rest.first;

    await script.appledoc(
      pro,
      compy,
      out,
      input,
      company_id: id,
      company_url: url,
      target: target,
    );

    return;
  }

  String getArgValue(String arg) {
    return argResults.wasParsed(arg)
        ? argResults[arg]
        : argParser.getDefault(arg);
  }
}
